
package net.goutalk.glcs.common.model.result;

import net.goutalk.glcs.common.enums.ResponseCode;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.util.HashMap;

/**
 * 返回数据
 *
 * @author tanyujie
 */
public class R extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;
	
	public R() {
		put("code", 0);
		put("success", true);
		put("msg", "");
	}
	
	public static R error() {
		return error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(), "未知异常，请联系管理员");
	}
	
	public static R error(String msg) {
		return error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(), msg);
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.put("code", code);
		r.put("msg", msg);
		r.put("data",null);
		return r;
	}

	public static R ok(String msg,Object result) {
		R r = new R();
		r.put("msg", msg);
		r.put("data",result);
		return r;
	}

	public static R ok(Object result) {
		R r = new R();
		r.put("msg", "");
		r.put("data",result);
		return r;
	}
	
//	public static R ok(Map<String, Object> map) {
//		R r = new R();
//		r.put("data",map);
//		return r;
//	}
	
	public static R ok() {
		return new R().put("data",null);
	}

	public static ResponseEntity<byte[]> fileStream(byte[] bot, String fileName) {

		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", fileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

		return new ResponseEntity<byte[]>(bot, headers, HttpStatus.OK);
	}

	@Override
	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	public Object getData(){
		return this.get("data");
	}

}
